const router = require('koa-router')()
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const axios = require('axios')
const request = require('request')
const path = require('path')
/**
 * 一个登陆接口，根据用户携带的不同的type测试
 * type = 1;  普通用户
 * type = 0; 微信用户
 *
 *
 */

// wx7f6f1534718f3ee2
const wxConfig = {
	appId: 'wx7f6f1534718f3ee2',
	appSecret: 'd4f138321eb2b403a9b177f59d2db5be'
}

// api/wx/login post
router.prefix('/wx')

// 图片接受地址接口
router.post('/uploadimg', async (ctx) => {
	const files = ctx.request.files
	const filePathName = path.basename(files.file.path)
	ctx.body = {
		data: {
			filePathName,
			url: ctx.origin + '/uploads/' + filePathName
		},
		code: 0
	}
})

router.get('/test', async (ctx) => {
	console.log('我是接口')
	console.log('ctx.:--------------->', ctx.query)
	ctx.body = {
		data: '接口信息',
		code: 0
	}
})

// 用户登录
router.get('/login', async (ctx) => {
	console.log('微信后台接口')
	try {
		// 1. 接收临时身份id
		const { code } = ctx.query
		// 2. 后台获取code请求 auth.code2Session接口，获取到openid secretKey,将这两个东西包装成一个登陆的token，
		// 返回给前端
		const requestUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.appId}&secret=${wxConfig.appSecret}&js_code=${code}&grant_type=authorization_code`
		const result = await axios.post(requestUrl)
		console.log('result:', result.data)
		const token = jwt.sign({ session_key: result.data.session_key }, 'immoc', {
			expiresIn: '1h'
		})
		ctx.body = {
			data: {
				token
			},
			msg: 'success'
		}
	} catch (error) {
		ctx.body = {
			msg: error
		}
	}
})

module.exports = router
